#include "ResourceSaver.h"
#include <QFile>
#include <QDir>
#include <iostream>
#include "CommonExceptions.h"
#include "ResourceManager.h"



_NS_OOP_BEGIN



ResourceSaver::ResourceSaver ()
{
}



void
ResourceSaver::saveObject (P_Object p_obj)
{
	if (p_obj == NULL)
		return;
	if (p_obj->_syncStatus == Object::NOT_CHANGED) {
#ifdef OOPUTILS_DEBUG
		std::cout << "Object " << p_obj->name ().toStdString () << " not changed" << std::endl;
#endif
		return;
	}
	
	if (p_obj->_syncStatus == Object::NEW)
		ResourceManager::ref ()._checkAndCorrectName (p_obj);

#ifdef OOPUTILS_DEBUG
	std::cout << "Save object " << p_obj->name ().toStdString () << std::endl;
#endif
	auto filePath = QDir (ResourceManager::ref ()._dir).filePath (p_obj->name ());
	QFile file (filePath);
	if (!file.open (QFile::WriteOnly))
		OOPTHROW (InvalidArgumentException (
				QString ("The file '%1' cannot be opened for write")
						.arg (filePath)));
	_outStream.setDevice (&file);
	_outStream << QString (typeid (*p_obj._getPtrToRealObject ()).name ());
	p_obj->write (*this);
	p_obj->_syncStatus = Object::NOT_CHANGED;
}



_NS_OOP_END